#include "th_ipt113_i.h"
#include "ui_th_ipt113_i.h"
#include <QDebug>
#include <QFileInfo>
#include <QSettings>
#include <QMessageBox>

TH_IPT113_I::TH_IPT113_I(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::TH_IPT113_I)
{
    ui->setupUi(this);
    initialize();
}

void TH_IPT113_I::initialize()
{
    this->setWindowTitle(tr("轨道电压相角模块(TH-IPT113-I)测试工具"));
    //    this->setFixedSize(412, 415);
    this->ui->statusBar->showMessage(tr("请连接分机！"));
    this->time.setInterval(2000);

    connect(ui->pushButton, &QPushButton::clicked, this, &TH_IPT113_I::on_pushButton);
    connect(ui->lineEdit_remoteIP, &QLineEdit::editingFinished, this, &TH_IPT113_I::on_remoteIPChanged);
    connect(&this->time, &QTimer::timeout, this, &TH_IPT113_I::on_testTimeout);
    connect(&socket, &QUdpSocket::readyRead, this, &TH_IPT113_I::on_socketReceive);
    connect(ui->spinBox, SIGNAL(valueChanged(int)), this, SLOT(on_spinBoxChanged(int)));
    connect(ui->checkBox, &QCheckBox::toggled, this, &TH_IPT113_I::on_AutoTest);
    connect(ui->groupBox_GR,&QGroupBox::toggled,this,&TH_IPT113_I::on_GroupBox_GR);
    readConfig();
    loadName();
}

TH_IPT113_I::~TH_IPT113_I()
{
    delete ui;
}

TH_IPT113_I::DataFrame TH_IPT113_I::toDataFrame(QByteArray array)
{
    TH_IPT113_I::DataFrame ret;

    if(!(array.size() == 34 || array.size() == 50)) {
        qDebug() << "轨道电压相角采集模块数据不完整：" << array.data();
        return ret;
    }


    //将原来的qint16改为quint16,因为当相角值>32767时会出现负数。
    quint16 *pdata;
    pdata = (quint16 *)array.data();

    ret.JBDY    = (float) * pdata * 0.018;     //电压值 = 值*量程/11000    量程：200
    ret.GD1_DY  = (float) * (pdata + 1) * 0.01;
    ret.GD2_DY  = (float) * (pdata + 2) * 0.01;
    ret.GD3_DY  = (float) * (pdata + 3) * 0.01;
    ret.GD4_DY  = (float) * (pdata + 4) * 0.01;
    ret.GD5_DY  = (float) * (pdata + 5) * 0.01;
    ret.GD6_DY  = (float) * (pdata + 6) * 0.01;
    ret.GD7_DY  = (float) * (pdata + 7) * 0.01;
    ret.GD1_XJ  = (float) * (pdata + 8) * 0.01;
    ret.GD2_XJ  = (float) * (pdata + 9) * 0.01;
    ret.GD3_XJ  = (float) * (pdata + 10) * 0.01;
    ret.GD4_XJ  = (float) * (pdata + 11) * 0.01;
    ret.GD5_XJ  = (float) * (pdata + 12) * 0.01;
    ret.GD6_XJ  = (float) * (pdata + 13) * 0.01;
    ret.GD7_XJ  = (float) * (pdata + 14) * 0.01;
    ret.JBPL    = (float) * (pdata + 15) * 0.01;
    ret.KGL     = (float) * (pdata + 16);

    if(array.size() == 50) {
        ret.GR1 = (float) * (pdata + 17) * 0.01;
        ret.GR2 = (float) * (pdata + 18) * 0.01;
        ret.GR3 = (float) * (pdata + 19) * 0.01;
        ret.GR4 = (float) * (pdata + 20) * 0.01;
        ret.GR5 = (float) * (pdata + 21) * 0.01;
        ret.GR6 = (float) * (pdata + 22) * 0.01;
        ret.GR7 = (float) * (pdata + 23) * 0.01;
        ret.GR8 = (float) * (pdata + 24) * 0.01;
    }

    return ret;
}

void TH_IPT113_I::setStatus(quint16 byteStatue)
{
    if(byteStatue & 1 << 0) {
        ui->checkBox_1->setChecked(true);
        ui->checkBox_1->setText(tr("占用"));
    } else {
        ui->checkBox_1->setChecked(false);
        ui->checkBox_1->setText(tr("空闲"));
    }

    if(byteStatue & 1 << 1) {
        ui->checkBox_2->setChecked(true);
        ui->checkBox_2->setText(tr("占用"));
    } else {
        ui->checkBox_2->setChecked(false);
        ui->checkBox_2->setText(tr("空闲"));
    }

    if(byteStatue & 1 << 2) {
        ui->checkBox_3->setChecked(true);
        ui->checkBox_3->setText(tr("占用"));
    } else {
        ui->checkBox_3->setChecked(false);
        ui->checkBox_3->setText(tr("空闲"));
    }

    if(byteStatue & 1 << 3) {
        ui->checkBox_4->setChecked(true);
        ui->checkBox_4->setText(tr("占用"));
    } else {
        ui->checkBox_4->setChecked(false);
        ui->checkBox_4->setText(tr("空闲"));
    }

    if(byteStatue & 1 << 4) {
        ui->checkBox_5->setChecked(true);
        ui->checkBox_5->setText(tr("占用"));
    } else {
        ui->checkBox_5->setChecked(false);
        ui->checkBox_5->setText(tr("空闲"));
    }

    if(byteStatue & 1 << 5) {
        ui->checkBox_6->setChecked(true);
        ui->checkBox_6->setText(tr("占用"));
    } else {
        ui->checkBox_6->setChecked(false);
        ui->checkBox_6->setText(tr("空闲"));
    }

    if(byteStatue & 1 << 6) {
        ui->checkBox_7->setChecked(true);
        ui->checkBox_7->setText(tr("占用"));
    } else {
        ui->checkBox_7->setChecked(false);
        ui->checkBox_7->setText(tr("空闲"));
    }
}

void TH_IPT113_I::setDisplay(DataFrame data)
{
    ui->lineEdit_JB->setText(QString::number(data.JBDY, 'f', 2));
    ui->lineEdit_DY1->setText(QString::number(data.GD1_DY, 'f', 2));
    ui->lineEdit_DY2->setText(QString::number(data.GD2_DY, 'f', 2));
    ui->lineEdit_DY3->setText(QString::number(data.GD3_DY, 'f', 2));
    ui->lineEdit_DY4->setText(QString::number(data.GD4_DY, 'f', 2));
    ui->lineEdit_DY5->setText(QString::number(data.GD5_DY, 'f', 2));
    ui->lineEdit_DY6->setText(QString::number(data.GD6_DY, 'f', 2));
    ui->lineEdit_DY7->setText(QString::number(data.GD7_DY, 'f', 2));
    ui->lineEdit_XJ1->setText(QString::number(data.GD1_XJ, 'f', 2));
    ui->lineEdit_XJ2->setText(QString::number(data.GD2_XJ, 'f', 2));
    ui->lineEdit_XJ3->setText(QString::number(data.GD3_XJ, 'f', 2));
    ui->lineEdit_XJ4->setText(QString::number(data.GD4_XJ, 'f', 2));
    ui->lineEdit_XJ5->setText(QString::number(data.GD5_XJ, 'f', 2));
    ui->lineEdit_XJ6->setText(QString::number(data.GD6_XJ, 'f', 2));
    ui->lineEdit_XJ7->setText(QString::number(data.GD7_XJ, 'f', 2));
    ui->lineEdit_PL->setText(QString::number(data.JBPL, 'f', 2));

    if(ui->groupBox_GR->isChecked()) {
        ui->lineEdit_GR1->setText(QString::number(data.GR1,'f',2));
        ui->lineEdit_GR2->setText(QString::number(data.GR2,'f',2));
        ui->lineEdit_GR3->setText(QString::number(data.GR3,'f',2));
        ui->lineEdit_GR4->setText(QString::number(data.GR4,'f',2));
        ui->lineEdit_GR5->setText(QString::number(data.GR5,'f',2));
        ui->lineEdit_GR6->setText(QString::number(data.GR6,'f',2));
        ui->lineEdit_GR7->setText(QString::number(data.GR7,'f',2));
        ui->lineEdit_GR8->setText(QString::number(data.GR8,'f',2));
    }else {
        ui->lineEdit_GR1->clear();
        ui->lineEdit_GR2->clear();
        ui->lineEdit_GR3->clear();
        ui->lineEdit_GR4->clear();
        ui->lineEdit_GR5->clear();
        ui->lineEdit_GR6->clear();
        ui->lineEdit_GR7->clear();
        ui->lineEdit_GR8->clear();
    }

    setStatus(data.KGL);
}

void TH_IPT113_I::clearDisplay()
{
    ui->spinBox->setRange(0, 0);

    ui->lineEdit_JB->clear();
    ui->lineEdit_DY1->clear();
    ui->lineEdit_DY2->clear();
    ui->lineEdit_DY3->clear();
    ui->lineEdit_DY4->clear();
    ui->lineEdit_DY5->clear();
    ui->lineEdit_DY6->clear();
    ui->lineEdit_DY7->clear();
    ui->lineEdit_XJ1->clear();
    ui->lineEdit_XJ2->clear();
    ui->lineEdit_XJ3->clear();
    ui->lineEdit_XJ4->clear();
    ui->lineEdit_XJ5->clear();
    ui->lineEdit_XJ6->clear();
    ui->lineEdit_XJ7->clear();
    ui->lineEdit_PL->clear();
    ui->lineEdit_GR1->clear();
    ui->lineEdit_GR2->clear();
    ui->lineEdit_GR3->clear();
    ui->lineEdit_GR4->clear();
    ui->lineEdit_GR5->clear();
    ui->lineEdit_GR6->clear();
    ui->lineEdit_GR7->clear();
    ui->lineEdit_GR8->clear();
    setStatus(0);
}

void TH_IPT113_I::readConfig()
{
    QFileInfo file("./cfg.ini");

    if(file.exists()) {
        QSettings *read = new QSettings("cfg.ini", QSettings::IniFormat);
        ui->lineEdit_remoteIP->setText(read->value("UDP/RemoteIP").toString());
        ui->spinBox_remotePort->setValue(read->value("UDP/RemotePort").toInt());
        bool temp = read->value("UDP/FixedLocalPort").toBool();
        ui->checkBox_localPort->setChecked(temp);
        ui->spinBox_localPort->setValue(read->value("UDP/LocalPort").toInt());

        delete read;
    } else {
        qDebug() << "cfg.ini 文件不存在！";
    }
}

void TH_IPT113_I::writeConfig()
{

    QSettings *writer = new QSettings("cfg.ini", QSettings::IniFormat);
    writer->setValue("UDP/RemoteIP", ui->lineEdit_remoteIP->text());
    writer->setValue("UDP/RemotePort", ui->spinBox_remotePort->value());

    if(ui->checkBox_localPort->isChecked()) {
        writer->setValue("UDP/FixedLocalPort", true);
    } else {
        writer->setValue("UDP/FixedLocalPort", false);
    }

    writer->setValue("UDP/LocalPort", ui->spinBox_localPort->value());

    delete writer;
}

void TH_IPT113_I::on_pushButton()
{
    if(socket.isValid()) {
        ui->checkBox->setChecked(false);
        this->time.stop();
        clearDisplay();
        socket.close();
        ui->groupBox->setEnabled(false);
        ui->lineEdit_remoteIP->setEnabled(true);
        ui->spinBox_remotePort->setEnabled(true);
        ui->checkBox_localPort->setEnabled(true);
        ui->spinBox_localPort->setEnabled(true);
        ui->pushButton->setText(tr("连接分机"));
        ui->statusBar->showMessage(tr("请重新连接分机!"));
    } else {
        if(ui->checkBox_localPort->isChecked()) {
            this->socket.bind(ui->spinBox_localPort->value());
        }

        this->socket.connectToHost(QHostAddress(ui->lineEdit_remoteIP->text()), ui->spinBox_remotePort->value());

        if(socket.isValid()) {
            writeConfig();
            ui->groupBox->setEnabled(true);
            ui->lineEdit_remoteIP->setEnabled(false);
            ui->spinBox_remotePort->setEnabled(false);
            ui->checkBox_localPort->setEnabled(false);
            ui->spinBox_localPort->setEnabled(false);
            ui->pushButton->setText(tr("断开连接"));
            ui->statusBar->showMessage(tr("\"回车\"进行1次测试!"));
        }
    }

}

void TH_IPT113_I::on_remoteIPChanged()
{
    QHostAddress ip(ui->lineEdit_remoteIP->text());

    if(ip.toString() != NULL) {
        this->ui->lineEdit_remoteIP->setText(ip.toString());
    } else {
        QMessageBox::warning(this, tr("错误："), tr("输入的分机IP地址有误，请重新输入!"), QMessageBox::Ok);
        ui->lineEdit_remoteIP->setFocus();
    }
}

void TH_IPT113_I::startOneTest()
{
    qDebug() << "开始一次手动测试……";
    this->ui->statusBar->showMessage(tr("正在测试……"));
    char code[2];
    code[0] = 0x01;
    code[1] = 0xA4;
    socket.writeDatagram(code, 2, QHostAddress(ui->lineEdit_remoteIP->text()), ui->spinBox_remotePort->value());
    qDebug() << "开起定时器……";
    this->time.start();
}

void TH_IPT113_I::on_testTimeout()
{
    qDebug() << "分机超时未响应……";
    this->statusBar()->showMessage(tr("分机超时未响应……请确认分机ip及端口号是否正确,分机是否在正常工作！"));
    this->time.stop();
    this->arrayData.clear();
    ui->spinBox->setRange(0, 0);
    ui->spinBox->setValue(0);

    if(ui->checkBox->isChecked()) {
        startOneTest();
    }
}

void TH_IPT113_I::keyPressEvent(QKeyEvent *event)
{
    if(!socket.isValid()) return;

    if(ui->checkBox->isChecked()) return;

    if(event->key() == Qt::Key_Return && !time.isActive()) {
        startOneTest();
    }
}

void TH_IPT113_I::on_spinBoxChanged(int arg)
{
    if(this->arrayData.isEmpty()) {
        ui->spinBox->setRange(0, 0);
        clearDisplay();
    } else {
        DataFrame dat;
        if(ui->groupBox_GR->isChecked()){
            dat = this->toDataFrame((arrayData.mid((arg - 1) * 50, 50)));

        }else{
            dat = this->toDataFrame((arrayData.mid((arg - 1) * 34, 34)));
        }
        setDisplay(dat);
    }
    setName(arg*7-6);
}

void TH_IPT113_I::on_socketReceive()
{
    qDebug() << "收到数据……";
    QByteArray ret;
    ret.resize(socket.pendingDatagramSize());
    QHostAddress ip;
    quint16 port;
    DataFrame dat;

    socket.readDatagram(ret.data(), socket.pendingDatagramSize(), &ip, &port);
    //    qDebug() << ret;

    if(ret.isEmpty())return;

    if(ret.at(0) != 0x00 || ret[1] != (char)0xA4) {
        ui->statusBar->showMessage(tr( "非轨道电压相角数据包……"));
        return;
    }

    //    quint16 len = (((quint16)ret.[3]<<8))+ret[2];//当ret[3]=00时会出错
    quint16 *plen = (quint16*)ret.data();
    quint16 len = *(plen + 1);

    if(len == 0x00) {
        ui->statusBar->showMessage(tr("分机未配置轨道电压相角模块,请检查分机配置！"));
        this->time.stop();
        return;
    }


    if(len * 2 != ret.size() - 4) {
        ui->statusBar->showMessage(tr( "非完整的轨道电压相角数据包……"));
        return;
    }

    this->arrayData = ret.mid(4);
    if(ui->groupBox_GR->isChecked())
    {
        ui->spinBox->setRange(1, len / 25);
    }else{
        ui->spinBox->setRange(1, len / 17);
    }
    ui->statusBar->showMessage(tr("测试完成！"));
    if(ui->groupBox_GR->isChecked()) {
        dat = toDataFrame(arrayData.mid((ui->spinBox->value() - 1) * 50, 50));
    }else{
        dat = toDataFrame(arrayData.mid((ui->spinBox->value() - 1) * 34, 34));
    }
    setDisplay(dat);

    if(ui->checkBox->isChecked()) {
        startOneTest();
    } else {
        this->time.stop();
    }
}

void TH_IPT113_I::on_AutoTest()
{
    startOneTest();
}

void TH_IPT113_I::loadName()
{
    QFileInfo file("DataName.ini");

    if(file.exists()) {
        QSettings *read = new QSettings("DataName.ini", QSettings::IniFormat);
        read->setIniCodec("GBK");
        read->beginGroup("TH-IPT113-I");
        foreach(QString item, read->childKeys()) {
            this->name.insert(item.toInt(), read->value(item).toString());
        }
        //        qDebug() << this->name;
    } else {
        qDebug() << "DataName.ini配置文件不存在！";
    }
}

void TH_IPT113_I::setName(unsigned int arg)
{
    if(0 == arg) {
        ui->label_1->setText("轨道1:");
        ui->label_2->setText("轨道2:");
        ui->label_3->setText("轨道3:");
        ui->label_4->setText("轨道4:");
        ui->label_5->setText("轨道5:");
        ui->label_6->setText("轨道6:");
        ui->label_7->setText("轨道7:");
        ui->label_GR1->setText("轨道1:");
        ui->label_GR2->setText("轨道2:");
        ui->label_GR3->setText("轨道3:");
        ui->label_GR4->setText("轨道4:");
        ui->label_GR5->setText("轨道5:");
        ui->label_GR6->setText("轨道6:");
        ui->label_GR7->setText("轨道7:");
    } else {
        if(this->name.contains(arg)) {
            ui->label_1->setText(this->name.value(arg) + ":");
        } else {
            ui->label_1->setText("轨道1:");
        }
        if(this->name.contains(arg+1)) {
            ui->label_2->setText(this->name.value(arg+1) + ":");
        } else {
            ui->label_2->setText("轨道2:");
        }
        if(this->name.contains(arg+2)) {
            ui->label_3->setText(this->name.value(arg+2) + ":");
        } else {
            ui->label_3->setText("轨道3:");
        }
        if(this->name.contains(arg+3)) {
            ui->label_4->setText(this->name.value(arg+3) + ":");
        } else {
            ui->label_4->setText("轨道4:");
        }
        if(this->name.contains(arg+4)) {
            ui->label_5->setText(this->name.value(arg+4) + ":");
        } else {
            ui->label_5->setText("轨道5:");
        }
        if(this->name.contains(arg+5)) {
            ui->label_6->setText(this->name.value(arg+5) + ":");
        } else {
            ui->label_6->setText("轨道6:");
        }
        if(this->name.contains(arg+6)) {
            ui->label_7->setText(this->name.value(arg+6) + ":");
        } else {
            ui->label_7->setText("轨道7:");
        }
        if(ui->groupBox_GR->isChecked()){
            if(this->name.contains(arg)) {
                ui->label_GR1->setText(this->name.value(arg) + ":");
            } else {
                ui->label_GR1->setText("轨道1:");
            }
            if(this->name.contains(arg+1)) {
                ui->label_GR2->setText(this->name.value(arg+1) + ":");
            } else {
                ui->label_GR2->setText("轨道2:");
            }
            if(this->name.contains(arg+2)) {
                ui->label_GR3->setText(this->name.value(arg+2) + ":");
            } else {
                ui->label_GR3->setText("轨道3:");
            }
            if(this->name.contains(arg+3)) {
                ui->label_GR4->setText(this->name.value(arg+3) + ":");
            } else {
                ui->label_GR4->setText("轨道4:");
            }
            if(this->name.contains(arg+4)) {
                ui->label_GR5->setText(this->name.value(arg+4) + ":");
            } else {
                ui->label_GR5->setText("轨道5:");
            }
            if(this->name.contains(arg+5)) {
                ui->label_GR6->setText(this->name.value(arg+5) + ":");
            } else {
                ui->label_GR6->setText("轨道6:");
            }
            if(this->name.contains(arg+6)) {
                ui->label_GR7->setText(this->name.value(arg+6) + ":");
            } else {
                ui->label_GR7->setText("轨道7:");
            }
        }
    }
}

void TH_IPT113_I::on_GroupBox_GR(bool checked) {
    if (checked){
        startOneTest();
    }else{
        ui->lineEdit_GR1->clear();
        ui->lineEdit_GR2->clear();
        ui->lineEdit_GR3->clear();
        ui->lineEdit_GR4->clear();
        ui->lineEdit_GR5->clear();
        ui->lineEdit_GR6->clear();
        ui->lineEdit_GR7->clear();
        ui->lineEdit_GR8->clear();
        startOneTest();
    }
}
